package com.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import hyl.core.MyFun;
import ini.My;

@Component
public class DemoDao {

	@SuppressWarnings("rawtypes")
	//第1种写法 返回 [[value1,value2,...],[...],[...],...]
	//这种写法节约传输的内容,但是顺序必须与前端保持一致
	public List<List<Object>> list(Map<String, String> ps) {

		String sql = "SELECT * FROM user_inf";
		List<Object> objs=new ArrayList<Object>();
		if (ps == null||ps.isEmpty()) {
			sql = sql+"limit 200";
		}else {			
			if (ps.get("where")!=null){
				sql =  sql+" where name like ? or userid like ?";			
				objs.add("%" + ps.get("where") + "%");
				objs.add("%" + ps.get("where") + "%");		
			}
			if (ps.get("rs_index")!=null){
				sql =  sql+" limit ?,?";			
				objs.add(MyFun.str2long(ps.get("rs_index")));
				objs.add(MyFun.str2long(ps.get("rs_size")));		
			}
			else {
				sql = sql+"limit 200";
			}
		}
		//System.out.println(sql);
		//System.out.println(objs);
		List<List<Object>> d = My.getDb1().queryList2D(sql, objs.toArray());
		System.out.println(JSON.toJSONString(d));
		return d;
	}
	//第二种写法 返回 [{key:value,key:value,...},{...},{...},...]
	//这种写法传输的内容偏多,但是顺序可以随意
	public List<Map<String, Object>> select(Map<String, String> ps) {
		String sql = "SELECT * FROM user_inf";
		List<Object> objs=new ArrayList<Object>();
		if (ps == null||ps.isEmpty()) {
			sql = sql+"limit 200";
		}else {			
			if (ps.containsKey("where")){
				sql =  sql+" where name like ? or userid like ?";			
				objs.add("%" + ps.get("where") + "%");
				objs.add("%" + ps.get("where") + "%");		
			}
			if (ps.containsKey("rs_index")){
				sql =  sql+" limit ?,?";			
				objs.add( ps.get("rs_index"));
				objs.add(ps.get("rs_size"));		
			}
		}

		List<Map<String, Object>> d = My.getDb1().queryList(sql, objs.toArray());
		return d;
	}

	public long count(Object[] ps) {
		String sql;
		if (ps == null) {
			sql = "SELECT count(*) cnt FROM user_inf ";
		} else {
			sql = "SELECT count(*) cnt FROM user_inf where name like ? or userid like ?";
			ps[0] = "%" + ps[0] + "%";
			ps[1] = "%" + ps[1] + "%";
		}

		long cnt = (long) My.getDb1().querySingle(sql, ps);
		return cnt;
	}

	public void update(Object[] ps) {
		// TODO Auto-generated method stub

	}

	public long insertUser(Object[] ps) {
		String sql = "insert into user_inf(userid,name,contact,pass) values(?,?,?,?)";
		return My.getDb1().executeUpdate(sql, ps);
	}

}
